package com.moleq.test;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.moleq.adapter.SaleListViewAdapter;
import com.moleq.base.OnResultListener;
import com.moleq.base.SmartBeep;
import com.moleq.dialog.MessageBox;
import com.moleq.enums.TransactionType;
import com.moleq.logic.MoleQConstants;
import com.moleq.logic.SaleList;
import com.moleq.logic.TransactionManager;
import com.moleq.logic.SaleList.OnItemDisplayListener;
import com.moleq.mgpos.widget.SaleListItemViewCache;
import com.moleq.models.GlobalInfo;
import com.moleq.models.SaleListItem;
import com.moleq.mgpos.activities.R;
import com.moleq.util.MoleQUtil;

public class SaleListView extends LinearLayout implements OnItemDisplayListener {

	/*
	 * // sale list adapter class SaleListViewAdapter extends BaseAdapter {
	 * 
	 * public SaleListViewAdapter(Context context) { mContext = context; }
	 * 
	 * @Override public int getCount() { return mData.getItemCount(); }
	 * 
	 * @Override public Object getItem(int arg0) { return mData.getItem(arg0); }
	 * 
	 * @Override public long getItemId(int arg0) { return arg0; }
	 * 
	 * @Override public View getView(int position, View convertView, ViewGroup
	 * parent) {
	 * 
	 * SaleListItemViewCache viewCache; View rowView = convertView;
	 * 
	 * // if(rowView == null){ rowView =
	 * mInflater.inflate(R.layout.sale_list_item, null);
	 * rowView.setOnTouchListener(onItemTouchListener); viewCache = new
	 * SaleListItemViewCache(rowView); rowView.setTag(viewCache); // }else{ //
	 * viewCache = (SaleListItemViewCache) rowView.getTag(); // }
	 * 
	 * viewCache.getTextViewEntryNum().setText(String.valueOf(position+1));
	 * viewCache
	 * .getTextViewQty().setText(String.valueOf(mData.getItem(position).
	 * getQty())); //
	 * viewCache.getTextViewName().setText(String.valueOf(mData.getItem
	 * (position).getName()));
	 * 
	 * String sContent = mData.getItem(position).getDisplayContent() + "   " +
	 * mData.getItem(position).getPriceDescription();
	 * viewCache.getTextViewName().setText(sContent);
	 * 
	 * viewCache.getTextViewPrice().setText("" +
	 * MoleQUtil.fixNumber(mData.getItem(position).getPrice()));
	 * viewCache.getButtonDelete().setTag(position);
	 * viewCache.getButtonDelete().setOnClickListener(mOnClickListener);
	 * viewCache.setDisplayControls(mIsShowItemOptions);
	 * viewCache.setSelected(false);
	 * 
	 * if (position == mSelectIndex) { viewCache.setSelected(true); } // else {
	 * // viewCache.setSelected(false); // } viewCache.setPosition(position);
	 * 
	 * return rowView;
	 * 
	 * }
	 * 
	 * }
	 */

	private LayoutParams LP_FF = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
	private SaleListViewAdapter mAdapter;
	private Context mContext;
	private SaleList mData;
	private LayoutInflater mInflater;
	private boolean mIsShowItemOptions;
	private ListView mListView;
	private int mSelectIndex = -1;
	private TransactionManager mTransMgr;
	private View mView;

	private OnClickListener mOnClickListener = new OnClickListener() {

		public void onClick(View v) {

			switch (v.getId()) {

			case R.id.buttonSaleItemDelete:

				confirmDelete();

				int deletePosition = (Integer) v.getTag();
				scrollToRow(deletePosition);
				removeItem(deletePosition);
				break;
			}

		}

	};

	private OnItemClickListener onItemClickListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			scrollToRow(arg2);

		}
	};

	private OnTouchListener onItemTouchListener = new OnTouchListener() {

		@Override
		public boolean onTouch(View v, MotionEvent event) {
			if (event.getAction() == MotionEvent.ACTION_DOWN) {
				SmartBeep.getInstance().play(SmartBeep.SOUND_CLICK);
			}
			return false;
		}

	};

	private TextView tvCashier, tvTotal, tvSubTotal, tvTax, tvDiscount, tvDiscount_num, tvtrnstype;
	private TextView tvLabelCoupon;
	private TextView tvLabelDiscount;
	private TextView tvLabelPrice;
	private TextView tvLabelSubtotal;
	private TextView tvLabelTax;
	private TextView tvLabelTotal;

	public SaleListView(Context context, SaleList dataSource) {
		super(context);

		mContext = context;
		mData = dataSource;
		if (mData == null) {
			mData = new SaleList();
		}

		constructor();

	}

	private void confirmDelete() {
		// TODO Auto-generated method stub

	}

	private void constructor() {

		mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

		mTransMgr = TransactionManager.getInstance();

		mView = mInflater.inflate(R.layout.sale_list, null);
		mListView = (ListView) mView.findViewById(R.id.lv_list);
		tvCashier = (TextView) mView.findViewById(R.id.tv_cashier_num);

		tvLabelPrice = (TextView) mView.findViewById(R.id.tvLabelPrice);
		tvLabelPrice.setText(String.format(this.mContext.getResources().getString(R.string.label_price), GlobalInfo.getInstance().CurrencySymbol));

		tvLabelSubtotal = (TextView) mView.findViewById(R.id.tvLabelSubtotal);
		tvLabelSubtotal.setText(String.format(this.mContext.getResources().getString(R.string.label_subtotal), GlobalInfo.getInstance().CurrencySymbol));

		tvLabelDiscount = (TextView) mView.findViewById(R.id.tvLabelDiscount);
		tvLabelDiscount.setText(String.format(this.mContext.getResources().getString(R.string.label_discount), GlobalInfo.getInstance().CurrencySymbol));

		// tvLabelCoupon = (TextView)mView.findViewById(R.id.tvLabelCoupon);
		// tvLabelCoupon.setText(String.format(this.mContext.getResources().getString(R.string.label_coupon),
		// GlobalInfo.getInstance().CurrencySymbol));

		tvSubTotal = (TextView) mView.findViewById(R.id.tv_subtotal_num);
		tvTax = (TextView) mView.findViewById(R.id.tv_tax_num);
		tvLabelTax = (TextView) mView.findViewById(R.id.tvLableTax);
		tvLabelTax.setText(String.format(this.mContext.getResources().getString(R.string.label_tax), GlobalInfo.getInstance().CurrencySymbol));

		tvTotal = (TextView) mView.findViewById(R.id.tv_total_num);
		tvLabelTotal = (TextView) mView.findViewById(R.id.tvLabelTotal);
		tvLabelTotal.setText(String.format(this.mContext.getResources().getString(R.string.label_total), GlobalInfo.getInstance().CurrencySymbol));

		tvCashier = (TextView) mView.findViewById(R.id.tv_cashier_num);
		tvDiscount_num = (TextView) mView.findViewById(R.id.tv_discount_num);
		tvDiscount = (TextView) mView.findViewById(R.id.tvLabelDiscount);
		tvDiscount.setText(String.format(this.mContext.getResources().getString(R.string.label_discount), GlobalInfo.getInstance().CurrencySymbol));

		// tvCoupon = (TextView) mView.findViewById(R.id.tvLabelCoupon);
		tvDiscount.setText(String.format(this.mContext.getResources().getString(R.string.label_coupon), GlobalInfo.getInstance().CurrencySymbol));

		// tvCoupon_num = (TextView) mView.findViewById(R.id.tv_coupon_num);
		tvtrnstype = (TextView) mView.findViewById(R.id.tv_trns_type);

		mAdapter = new SaleListViewAdapter(mContext);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(onItemClickListener);

		mView.setLayoutParams(LP_FF);
		mView.setBackgroundColor(Color.WHITE);

		setLayoutParams(LP_FF);
		setOrientation(VERTICAL);
		addView(mView);

	}

	private boolean mLoadPendingItemMode = false;
	@Override
	public void onAnnounceCartChanges() {
		if (mLoadPendingItemMode)
			return;

		Log.i("com.ming.saleactivity", "onAnnounceCartChanges -> itemcount:" + mTransMgr.mSaleListItems.getItemCount());

		if (mTransMgr.mSaleListItems.getItemCount() == 0) {
//			showImage(null);
			mTransMgr.setBirthdayDate("");
		}
		
//		refreshDisplayContent();
	}
	
	@Override
	public void onNoItemInList() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onSelectedIndex(int idx) {
		scrollToRow(idx);

	}

	@Override
	public void onShowItem(SaleListItem item) {

	}

	// refresh view
	public void refreshDisplayContent() {
		tvSubTotal.setText(MoleQUtil.fixNumber(mTransMgr.getSubTotal()));
		tvTax.setText(MoleQUtil.fixNumber(mTransMgr.getTotalTax()));
		tvTotal.setText(MoleQUtil.fixNumber(mTransMgr.getAmountPayable()));
		// =====code by feng =======
		if (mTransMgr.getTransDiscount() * -1 > 0) {
			tvDiscount_num.setVisibility(VISIBLE);
			tvDiscount.setVisibility(VISIBLE);
			tvDiscount.setText(mTransMgr.TransDntValue + "% " + String.format(this.mContext.getResources().getString(R.string.label_discount), GlobalInfo.getInstance().CurrencySymbol));
			tvDiscount_num.setText(MoleQUtil.fixNumber(mTransMgr.getTransDiscount()));
		} else {
			tvDiscount_num.setVisibility(INVISIBLE);
			tvDiscount.setVisibility(INVISIBLE);
			tvDiscount_num.setText("");
			mTransMgr.TransDntType = "";
			mTransMgr.TransDntValue = 0;
		}

		// if (mTransMgr.getCoupon() * -1 > 0) {
		// tvCoupon_num.setVisibility(VISIBLE);
		// tvCoupon.setVisibility(VISIBLE);
		// tvCoupon_num.setText(MoleQUtil.fixNumber(mTransMgr.getCoupon()));
		// }else{
		// tvCoupon_num.setVisibility(INVISIBLE);
		// tvCoupon.setVisibility(INVISIBLE);
		// tvCoupon_num.setText("");
		// mTransMgr.setCouponSetting(null);
		// }

		if (mTransMgr.TransType == TransactionType.RETURN) {
			tvtrnstype.setVisibility(VISIBLE);
		} else {
			tvtrnstype.setVisibility(INVISIBLE);
		}

	}

	// delete record
	public void removeItem(int position) {

		/*
		 * int row = mData.removeItem(position); if(row >= 0){ scrollToRow(row);
		 * mListView.setSelection(mSelectIndex);
		 * MessageBox.show(mContext,mContext
		 * .getResources().getString(R.string.msg_del_last_item));
		 * 
		 * }else if(row == SaleList.SUCCEED){ mAdapter.notifyDataSetChanged();
		 * scrollToRow(mData.getItemCount() - 1); refreshDisplayContent();
		 * 
		 * if(mContext instanceof OnResultListener){ OnResultListener linstener
		 * = (OnResultListener) this.mContext; //
		 * linstener.onActiveOption(FunctionOption.FUNC_VOID);
		 * 
		 * } // mActionLinstener.onItemClickLisener(FunctionOption.FUNC_VOID,
		 * 0); }
		 */
	}

	public void reset() {

		mSelectIndex = -1;
		mData.clear();
		mAdapter.notifyDataSetChanged();
		refreshDisplayContent();
	}

	public void scrollToRow(int row) {

		SaleListItemViewCache cache = null;
		for (int i = 0; i < mListView.getChildCount(); i++) {

			cache = (SaleListItemViewCache) mListView.getChildAt(i).getTag();
			cache.setSelected(false);
			if (row == cache.getPosition()) {
				cache.setSelected(true);
			}
		}

		mSelectIndex = row;

		if (row >= 0) {
			if (mContext instanceof OnResultListener) {
				OnResultListener linstener = (OnResultListener) this.mContext;
				linstener.onReturnValue(MoleQConstants.DISPLAY_SELECTED_ITEM, row);
			}
		}

		if (mSelectIndex == mData.getItemCount() - 1) {
			mListView.setSelection(mSelectIndex);
		}
	}

	public void setCashierText(String content) {
		tvCashier.setText("Cashier #: " + content);
	}

	public void setDataSource(SaleList list) {
		this.mData = list;
	}

	public void updateView(int itemIndex, boolean isShowControl) {
		int visiblePosition = mListView.getFirstVisiblePosition();
		View view = mListView.getChildAt(itemIndex - visiblePosition);
		SaleListItemViewCache cache = (SaleListItemViewCache) view.getTag();
		cache.setDisplayControls(isShowControl);
	}
	
	public void setShowControl(boolean bSwitch) {
		int visiblePosition = mListView.getFirstVisiblePosition();
		int showingRecordCnt = mListView.getChildCount();
		int visibleEndPostion = visiblePosition + showingRecordCnt;
		for (int i = visiblePosition; i < visibleEndPostion; i++) {
			updateView(i,bSwitch);
			
		}
	}
}
